<template>
  <el-upload
    :http-request="upload_http"
    :on-change="upload_change"
    :before-upload="upload_before"
    action="settled/uploadFile"
    :show-file-list="false"
  >
    <el-button size="small" type="primary" class="upload">上传</el-button>
  </el-upload>
</template>

<script>
import axios from "axios";
export default {
  props: {
    type: {
      type: String,
      default: "image"
    }
  },
  methods: {
    upload_http(file) {
      var from = new FormData();
      from.append("file", this.file);
      from.append("bucket", "dxtoss");
      axios({
        data: from,
        url: "starpapi/upload",
        method: "post"
      })
        .then(res => {
          this.$emit("urlChange", res);
        })
        .catch(res => {
          console.error(res);
        });
    },
    upload_change(file) {
      this.file = file.raw;
    },
    upload_before(file) {
      if (this.type === "image") {
        if (!/(gif|jpg|jpeg|png|gif|jpg|png)/.test(file.name)) {
          this.$message.error("请上传图片~");
          return false;
        }
        if (file.size / 1024 / 1024 > 3) {
          this.$message.error("上传图片大小不能超过 3MB!");
          return false;
        }
      } else if (this.type === "video") {
        if (
          [
            "video/mp4",
            "video/ogg",
            "video/flv",
            "video/avi",
            "video/wmv",
            "video/rmvb"
          ].indexOf(file.type) == -1
        ) {
          this.$message.error("请上传正确格式的视频");
          return false;
        }
      }
    }
  }
};
</script>